package com.mysteel.cart.controller;

import com.mysteel.cart.service.CartService;
import com.mysteel.cart.vo.Cart;
import com.mysteel.cart.vo.CartItem;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.servlet.mvc.support.RedirectAttributes;

import java.util.List;


/**
 * ProjectName: mail
 * ClassName: CartController
 * Description:
 * date: 2021/03/15/015 10:50
 *
 * @author xiaochao
 */
@Controller
public class CartController {

    @Autowired
    private CartService cartService;

    @ResponseBody
    @GetMapping("/currentUserCartItems")
    public List<CartItem> getCurrentUserCartItems(){
        return cartService.getCurrentUserCartItems();
    }

    @GetMapping("/checkItem")
    public String checkItem(@RequestParam("skuIds") String skuIds, @RequestParam("check") Integer check){
        cartService.checkItem(skuIds,check);
        return "redirect:http://cart.xcmail.com/cart.html";
    }

    @GetMapping("/countItem")
    public String countItem(@RequestParam("skuId") Long skuId, @RequestParam("count") Integer count){
        cartService.changeItemCount(skuId,count);
        return "redirect:http://cart.xcmail.com/cart.html";
    }

    @GetMapping("/deleteItem")
    public String deleteItem(@RequestParam("skuId") Long skuId){
        cartService.deleteItemBySkuId(skuId);
        return "redirect:http://cart.xcmail.com/cart.html";
    }

    /**
     * 浏览器有一个名为 user-key 的cookie，有效期为一个月
     * 如果第一次使用京东的购物车，都会分配一个 user-key 以后每次访问都会带上
     * @return
     */
    @GetMapping("cart.html")
    public String cartListPage(Model model){
        Cart cart = cartService.getUserCart();
        model.addAttribute("cart",cart);
        return "cartList";
    }

    /**
     * 添加购物车
     * @return
     */
    @RequestMapping("/addToCart")
    public String addToCart(Long skuId, Integer num, RedirectAttributes redirectAttributes){
        CartItem cartItem = cartService.addToCart(skuId, num);
        redirectAttributes.addAttribute("skuId",skuId);
        return "redirect:http://cart.xcmail.com/addToCartSuccess.html";
    }

    @GetMapping("/addToCartSuccess.html")
    public String addToCartSuccess(Long skuId,Model model){
        CartItem cartItem = cartService.getCartItemBySkuId(skuId);
        model.addAttribute("item",cartItem);
        return "success";
    }
}
